﻿using System;
using System.IO;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Windows;
using System.Windows.Input;
using System.Windows.Interop;
using Microsoft.Practices.Unity;
using TrackIT.Common;
using TrackIT.Common.Keyboard;

namespace TrackIT
{
    /// <summary>
    /// Interaction logic for App.xaml
    /// </summary>
    public partial class App : IDisposable
    {
        [DllImport("user32.dll")]
        private static extern bool UnregisterHotKey(IntPtr windowHandle, int id);

        private System.Windows.Forms.NotifyIcon notifyIcon;
        private ReportWindow reportWindow;
        private bool _isDisposed = false;

        private void Application_Startup(object sender, StartupEventArgs e)
        {
            TrackITInitialiser.Initialise();
            notifyIcon = new System.Windows.Forms.NotifyIcon();
            Stream iconStream = Assembly.GetExecutingAssembly().GetManifestResourceStream("TrackIT.Resources.preferences_system_time.ico");

            if (iconStream != null)
            {
                notifyIcon.Icon = new System.Drawing.Icon(iconStream);
                notifyIcon.Visible = true;
                System.Windows.Forms.MenuItem[] menuItems = 
                { 
                    new System.Windows.Forms.MenuItem("Generate Report", GenerateReport),
                    new System.Windows.Forms.MenuItem("Exit", UserExit)
                };
                notifyIcon.ContextMenu = new System.Windows.Forms.ContextMenu(menuItems);
            }

            reportWindow = TrackITContainer.Current.Resolve<ReportWindow>();
        }

        public void GenerateReport(object sender, EventArgs e)
        {
            reportWindow.Show();
        }

        public void UserExit(object sender, EventArgs e)
        {
            WindowInteropHelper winInterop = new WindowInteropHelper(MainWindow);
            if (winInterop.Handle.ToInt64() > 0)
            {
                HwndSource source = HwndSource.FromHwnd(winInterop.Handle);
                if (source != null)
                    UnregisterHotKey(source.Handle, 1);
            }
            notifyIcon.Visible = false;
            Current.Shutdown();   
        }

        public void GlobalKeyUp(object sender, RawKeyEventArgs e)
        {
            if (e.Key == Key.F19 || e.Key == Key.Scroll)
            {
                if (!MainWindow.IsVisible)
                {
                    MainWindow.Show();
                }
            }
        }

        void IDisposable.Dispose()
        {
            if (!_isDisposed)
            {
                notifyIcon.Dispose();
                _isDisposed = true;
            }
        }
    }
}
